package com.mike.bdb.ui;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.viewers.AbstractTreeViewer;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mike.bdb.manager.DBManager;
import com.mike.bdb.ui.provider.tree.TreeNode;
import com.mike.bdb.util.DataCurrent;
import com.mike.bdb.util.Folder;
import com.mike.bdb.util.ImageManager;
import com.mike.swt.util.ShellUtil;

public class SelectDialog {

	private static final Logger LOG = LoggerFactory.getLogger(SelectDialog.class);
	private static final String SPLIT = DBManager.BERKELEY_DATABASE_SECONDARY_INDEX_SPLIT_CHAR;
	private static final String PASS = DBManager.BERKELEY_DATABASE_DEFAULT_FORMAT;
	private static final String PASS_2 = DBManager.BERKELEY_DATABASE_DEFAULT_SEQUENCES;
	private Shell motherland;
	private TreeViewer treeViewer;
	private static Set<String> openedDatabase = new HashSet<String>();
	protected Shell	shell;

	private volatile boolean open = false;
	private Text text;
	private Label label_1;
	private Button button;
	
	private void updateTreeData() {
		if(null == treeViewer) return ;
		List<String> databases = DBManager.getInstance().getDatabases();
		String home = DBManager.getInstance().getHome();
		TreeNode root = new TreeNode(home, null);
		for (String database : databases) {
			if(database.endsWith(PASS)) {
				continue;
			}
			if(database.endsWith(PASS_2)) {
				continue;
			}
			if(database.contains(".")) {
				String[] split = database.split("\\.");
				String string = split[split.length - 1];
				if(string.contains(SPLIT)) {
					//不显示二级索引数据
					continue;
				}
			}
			new TreeNode(database, root);
		}
		if(null == root.getChild()) {
			alert("No data from Berkeley database Home:" + text.getText());
		} else {
			Set<TreeNode> list = DataCurrent.getInstance().openDatabase;
			list.add(root);
			treeViewer.setInput(list);
			treeViewer.expandToLevel(root, AbstractTreeViewer.ALL_LEVELS);
		}
	}
	
	public boolean isOpen() {
		return open;
	}

	public SelectDialog(Shell motherland, TreeViewer treeViewer) {
		this.motherland = motherland;
		this.treeViewer = treeViewer;
	}
	
	/**
	 * Launch the application.
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			SelectDialog window = new SelectDialog(null, null);
			window.open();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Open the window.
	 */
	public void open() {
		Display display = Display.getDefault();
		createContents();
		shell.open();
		open = true;
		shell.layout();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
		open = false;
	}

	/**
	 * Create contents of the window.
	 */
	protected void createContents() {
		shell = new Shell(SWT.CLOSE | SWT.BORDER | SWT.APPLICATION_MODAL);
		shell.setSize(460, 144);
		shell.setText(Messages.getString("SelectDialog.title")); //$NON-NLS-1$
		shell.setImage(ImageManager.getImage(ImageManager.ICON_DATABASE));
		shell.setLayout(new FillLayout(SWT.HORIZONTAL));
		{
			Composite composite = new Composite(shell, SWT.NONE);
			composite.setLayout(new GridLayout(7, false));
			new Label(composite, SWT.NONE);
			new Label(composite, SWT.NONE);
			new Label(composite, SWT.NONE);
			new Label(composite, SWT.NONE);
			new Label(composite, SWT.NONE);
			new Label(composite, SWT.NONE);
			new Label(composite, SWT.NONE);
			{
				label_1 = new Label(composite, SWT.NONE);
				label_1.setAlignment(SWT.RIGHT);
				{
					GridData gridData = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1);
					gridData.widthHint = 54;
					label_1.setLayoutData(gridData);
				}
				label_1.setText(Messages.getString("SelectDialog.label_1.text")); //$NON-NLS-1$
			}
			{
				text = new Text(composite, SWT.BORDER);
				text.setEditable(false);
				{
					GridData gridData = new GridData(SWT.LEFT, SWT.CENTER, false, false, 5, 1);
					gridData.widthHint = 304;
					text.setLayoutData(gridData);
				}
				text.setText(
						Folder.getFolder(DBManager.getInstance().getHome()).getAbsolutePath());
			}
			{
				button = new Button(composite, SWT.NONE);
				button.setText(Messages.getString("SelectDialog.button.text")); //$NON-NLS-1$
				{
					GridData gridData = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
					gridData.widthHint = 60;
					button.setLayoutData(gridData);
				}
				button.addSelectionListener(new SelectionAdapter() {
					@Override
					public void widgetSelected(SelectionEvent e) {
						DirectoryDialog dialog = new DirectoryDialog(shell);
						dialog.setFilterPath(text.getText());
						String open = dialog.open();
						if(null != open && !"".equals(open.trim())) {
							if(LOG.isDebugEnabled()) {
								LOG.debug("update home:" + open);
							}
							text.setText(open);
						}
					}
				});
				button.setImage(ImageManager.getImage(ImageManager.ICON_FOLDER));
				button.setFocus();
			}
			new Label(composite, SWT.NONE);
			new Label(composite, SWT.NONE);
			new Label(composite, SWT.NONE);
			new Label(composite, SWT.NONE);
			new Label(composite, SWT.NONE);
			new Label(composite, SWT.NONE);
			new Label(composite, SWT.NONE);
			new Label(composite, SWT.NONE);
			{
				Button btnok = new Button(composite, SWT.NONE);
				{
					GridData gridData = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
					gridData.widthHint = 108;
					btnok.setLayoutData(gridData);
				}
				btnok.addSelectionListener(new SelectionAdapter() {
					@Override
					public void widgetSelected(SelectionEvent e) {
						String databasePath = text.getText();
						if(openedDatabase.contains(databasePath)) {
							shell.dispose();
							return;
						}
						boolean updateHomeAndStore = DBManager.getInstance().updateHome(databasePath);
						if(updateHomeAndStore) {
							if(null != treeViewer) {
								updateTreeData();
							}
							openedDatabase.add(databasePath);
						} else {
							alert("Fail open Berkeley database Home:" + text.getText());
						}
						shell.dispose();
					}

				});
				btnok.setText(Messages.getString("SelectDialog.btnok.text")); //$NON-NLS-1$
				btnok.setImage(ImageManager.getImage(ImageManager.ICON_ACCEPT));
			}
			new Label(composite, SWT.NONE);
			new Label(composite, SWT.NONE);
			new Label(composite, SWT.NONE);
			new Label(composite, SWT.NONE);
			new Label(composite, SWT.NONE);
		}

		if(null != motherland) {
			ShellUtil.setCenter(shell, motherland);
		}
	}

	private void alert(String errorMessage) {
		if(null == errorMessage) return;
		if(LOG.isDebugEnabled()) {
			LOG.debug(errorMessage);
		}
		if(null != shell) {
			shell.setVisible(false);
		}
		Status status = new Status(IStatus.ERROR, 
				Messages.getString("Motherland.motherland.text") + DataCurrent.VERSION,
				0,
				errorMessage, null);
        ErrorDialog.openError(Display.getCurrent().getActiveShell(),
        		Messages.getString("Motherland.motherland.text") + " " + DataCurrent.VERSION + " Error",
        		"", status);
	}
	
}
